package com.oss.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oss.PMF;
import com.oss.model.Tag;

/**
 * @author xueqiang.mi
 * @date 2010-2-4
 */
public class TagService extends BaseService {

	public void add(Tag tag) {
		PersistenceManager pm = PMF.get();
		try {
			tag.setId(generateId(tag.getId()));
			tag.setCreatedDate(new Date());
			pm.makePersistent(tag);
		} finally {
			pm.close();
		}
	}

	public Tag get(String id) {
		PersistenceManager pm = PMF.get();
		try {
			return pm.getObjectById(Tag.class, id);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Tag> getChildTags() {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Tag.class, "parent != :parent");
			Collection<Tag> c = pm.detachCopyAll((Collection<Tag>) query.execute("0"));
			return new ArrayList<Tag>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Tag> getChildTags(String id) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Tag.class, "parent == :parent");
			Collection<Tag> c = pm.detachCopyAll((Collection<Tag>) query.execute(id));
			return new ArrayList<Tag>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Tag> getRootTags() {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Tag.class, "parent == :parent");
			Collection<Tag> c = pm.detachCopyAll((Collection<Tag>) query.execute("0"));
			return new ArrayList<Tag>(c);
		} finally {
			pm.close();
		}
	}

	public List<Tag> getTagTree() {
		List<Tag> rootTags = this.getRootTags();
		for (Tag tag : rootTags) {
			tag.setChildren(this.getChildTags(tag.getId()));
		}
		return rootTags;
	}

	public void update(Tag tag) {
		PersistenceManager pm = PMF.get();
		try {
			Tag t = pm.getObjectById(Tag.class, tag.getId());
			t.setName(tag.getName());
			t.setDescription(tag.getDescription());
			t.setParent(tag.getParent());
		} finally {
			pm.close();
		}
	}
}
